import cron from "node-cron";
import { exec } from "child_process";
import ps from "ps-node";
import axios from "axios"; // 确保安装 axios 用于发送 HTTP 请求

// 爬虫配置数组，可以根据需要添加更多爬虫
// 添加格式为在package.json中配置的启动命令和对应的程序路径，如：npm run zcool-crawler-ts 以及./zcool-crawler/index.ts
//一次检测一个
const crawlers = [
  {
    script: "./src/www-51miz-com/index.ts",
    startCommand: "yarn miz-crawler-ts",
  },
];

// ==================自动化监听爬虫脚本=================

// 检查爬虫是否在运行
function checkCrawlerStatus(crawler) {
  return new Promise((resolve, reject) => {
    ps.lookup(
      {
        command: "node",
        arguments: crawler.script,
      },
      (err, resultList) => {
        if (err) {
          reject(err);
        } else {
          resolve(resultList.length > 0);
        }
      }
    );
  });
}

// 启动爬虫
function startCrawler(crawler) {
  try {
    exec(crawler.startCommand, (error, stdout, stderr) => {
      if (stderr) {
        console.error(`路径 ${crawler.name}错误：`, stderr);
      }
      console.log(`Output from ${crawler.name}:`, stdout);
    });
  } catch (e) {
    console.error(`启动 ${crawler.name} 失败:`, e);
  }
}

//设置定时任务:检测爬虫是否正在运行，如果没有运行，则启动爬虫（每分钟检查一次）
cron.schedule("0 * * * *", () => {
  console.log("监听爬虫状态...");
  crawlers.forEach(async (crawler) => {
    try {
      const isRunning = await checkCrawlerStatus(crawler);
      if (!isRunning) {
        console.log(`${crawler.name} 没有运行，开启爬虫...`);
        startCrawler(crawler);
      } else {
        console.log(`${crawler.name} 正在运行.`);
      }
    } catch (error) {
      console.error(`Error checking status for ${crawler.name}:`, error);
      pushToWeChat(
        `pixabay.com\ncookie可能过期需要人工介入！😭\n @邓雄威 来人！救虫啊！`
      );
    }
  });
});

// 启动时立即检查并启动爬虫
(async () => {
  crawlers.forEach(async (crawler) => {
    const isRunning = await checkCrawlerStatus(crawler);
    if (!isRunning) {
      console.log(`${crawler.name} 没有运行，开启爬虫...`);
      startCrawler(crawler);
    }
  });
})();

console.log("监听器已启动，开始检查爬虫状态...");

// 企业微信推送
export function pushToWeChat(content) {
  axios.post(
    "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=65ecab09-ed93-4417-859e-fce5ed1b68db",
    {
      msgtype: "text",
      text: { content },
    },
    { headers: { "Content-Type": "application/json" } }
  );
}
